import {AddNodeBtnClassName, DelNodeBtnClassName} from '../constant/index'
let NodeID = 0
import {createError} from '../util'

export const createNodeObj = (element, createdNode=null, creatByNode=null) => {
    return {
        nodeid: NodeID++,
        element,
        createdNode,
        creatByNode,
        addBtnEl: element.getElementsByClassName(AddNodeBtnClassName)[0],
        delBtnEl: element.getElementsByClassName(DelNodeBtnClassName)[0]
    }
}

export const clearNodeObj = (node) => {
    if (isNodeObj(node)){
        node.creatByNode && (node.creatByNode.createdNode = null)
        node.element = null
        node.createdNode = null
        node.creatByNode = null
        node.addBtnEl = null
        node.delBtnEl = null
        node = null
        return true
    }
    return false
}

export const appendNode = (parent, child) => {
    let isParentNode = isNodeObj(parent), isChildNode = isNodeObj(child)
    if (isParentNode && isChildNode){
        parent.element.appendChild(node.element)
        
    }else if (!isParentNode && isChildNode){
        parent.appendChild(child.element)
    }else if (isParentNode && !isChildNode){
        parent.element.appendChild(child)
    }else {
        parent.appendChild(child)
    }
}

export const removeNode = (parent, child) => {
    let isParentNode = isNodeObj(parent), isChildNode = isNodeObj(child)
    if (isParentNode && isChildNode){
        parent.element.removeChild(node.element)
        
    }else if (!isParentNode && isChildNode){
        parent.removeChild(child.element)
    }else if (isParentNode && !isChildNode){
        parent.element.removeChild(child)
    }else {
        parent.removeChild(child)
    }
}

/**
 * 
 * @param {vnode} node1 created by node2
 * @param {vnode} node2 create node1
 */
export const buildNodeRel = (node1, node2) => {
    if (isNodeObj(node1) && isNodeObj(node2)){
        node1.creatByNode = node2
        node2.createdNode = node1
    }else {
        throw createError(buildNodeRel, 'both node type should be vnode')
    }
}

export const isNodeObj = (node) => {
    return typeof node.nodeid === 'number'
}

export const findNodeByEl = (element, root) => {
    let currNode = root

    while(currNode){
        if (currNode.element === element){
            return currNode
        }
        currNode = currNode.createdNode
    }

    return null
}

